// src/utils/websocket.js

class WebSocketService {
  constructor() {
    this.socket = null
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectInterval = 3000 // 重连间隔3秒
  }

  // 初始化WebSocket连接
  connect(url) {
    if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
      this.socket = new WebSocket(url)

      // 连接成功回调
      this.socket.onopen = () => {
        console.log('WebSocket connected')
        this.reconnectAttempts = 0 // 重置重连计数器
      }

      // 接收消息回调
      this.socket.onmessage = (event) => {
        try {
          const message = JSON.parse(event.data)
          // 触发全局事件（用于跨组件通信）
          const customEvent = new CustomEvent('websocket-message', { detail: message })
          window.dispatchEvent(customEvent)
        } catch (error) {
          console.error('WebSocket message parse error:', error)
        }
      }

      // 错误处理
      this.socket.onerror = (error) => {
        console.error('WebSocket error:', error)
        this.reconnect(url)
      }

      // 连接关闭处理
      this.socket.onclose = (event) => {
        if (!event.wasClean) {
          console.log('WebSocket意外断开，尝试重连...')
          this.reconnect(url)
        }
      }
    }
  }

  // 重连机制
  reconnect(url) {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      setTimeout(() => {
        console.log(`尝试第 ${this.reconnectAttempts + 1} 次重连...`)
        this.reconnectAttempts++
        this.connect(url)
      }, this.reconnectInterval)
    } else {
      console.error('WebSocket重连次数已达上限，放弃连接')
    }
  }

  // 关闭连接
  disconnect() {
    if (this.socket) {
      this.socket.close()
      console.log('WebSocket主动断开')
    }
  }
}

export const webSocketService = new WebSocketService()
